<?php
/**
 * 这是一个执行查询的示例
 * User: ford
 * Date: 15-6-25
 * Time: 上午9:30
 */
$query = "SELECT e.ename, e.job, d.dname, d.loc FROM emp e JOIN dept d ON (d.deptno = e.deptno)";

$column_names = array();
$formats = array();
$ncols = 0;

try {
	$db = new SQLite3("scott.sqlite");
	$res = $db->query($query);
	if($db->lastErrorCode() != 0) {
		throw new Exception($db->lastErrorMsg());
	}

	//获取列数
	$ncols = $res->numColumns();
	//对于每一列，根据数据类型定义printf输出格式
	foreach(range(0, $ncols -1 ) as $i) {
		$column_names[$i] = $res->columnName($i);
		if($res->columnType($i) == SQLITE3_INTEGER) {
			$formats[$i] = "% 12d";
		}else {
			$formats[$i] = "% 12s";
		}
	}
	//打印列标题
	foreach($column_names as $topic) {
		printf("%12s", strtoupper($topic));
	}

	//打印分界线
	printf("\n% '-48s\n", '-');

	//打印记录
	while($row = $res->fetchArray(SQLITE3_NUM)) {
		foreach(range(0, $ncols -1) as $i) {
			printf($formats[$i], $row[$i]);
		}
		echo "\n";
	}

}
catch (Exception $e) {
	echo "Exception:\n";
	die($e->getMessage() . "\n");
}